package com.cmd;

import java.net.InetSocketAddress;

import io.netty.channel.Channel;

import com.alibaba.fastjson.JSONObject;
import com.player.User;
import com.player.WorldMgr;
import com.qy.util.StaticData;
import com.qy.util.WeiXinContants;
import com.qy.util.WeiXinUtil;
import com.service.MsgHandler;
import com.socket.Command;
import com.util.PBMessage;

/**
 * 用户登录
 * @author 34225_000
 *
 */
public class UserLoginCMD implements Command  {


	@Override
	public void execute(Channel channel, PBMessage packet) throws Exception {
		/*
		 * 根据openid获取用户
		 * 没有则生成一个用户
		 * 然後更新用戶的數據
		 */
		JSONObject reJs = new JSONObject();
		JSONObject param = packet.getMessage();
		if(!param.containsKey("weCode")||!param.containsKey("type")){
			reJs.put(StaticData.reKey.code.getKey(), StaticData.codeType.param_error.getType());
			WorldMgr.sendMsg(channel, reJs);
			return;
		}
		String weCode = param.getString("weCode");
		int type = param.getIntValue("type");
		JSONObject result = WeiXinUtil.getUserInfoToWidget(weCode,type);
		
		if(!result.containsKey("openid")){
			reJs.put(StaticData.reKey.code.getKey(), StaticData.codeType.not_exist.getType());
			WorldMgr.sendMsg(channel, reJs);
			return;
		}
		String openid = result.getString("openid");
		User user = WorldMgr.getGamePlayer(openid, type);
		if(user==null){
			user = WorldMgr.createGamePlayer(openid, type);
		}
		if(user==null){
			reJs.put(StaticData.reKey.code.getKey(), StaticData.codeType.not_exist2.getType());
			WorldMgr.sendMsg(channel, reJs);
			return;
		}
		/*
		 * 如果重复登陆
		 */
		if(user.getUserChannel()!=null){
			reJs.put(StaticData.reKey.code.getKey(), StaticData.codeType.Retype_Password.getType());
			WorldMgr.sendMsg(user.getUserChannel(), reJs);
			user.getUserChannel().close();
			MsgHandler.remove(user.getUserChannel());
		}
		user.setUserChannel(channel);
		MsgHandler.addChannel(channel, user.getID(),packet.getType());
		/*
		 * 用戶需要更新數據
		 */
		String image = null;
		String nickname = null;
		int sex = 0;
		if(type==StaticData.userType.COMMON_USER.getType()){
			if(!param.containsKey(WeiXinContants.headimgurl)
				||!param.containsKey(WeiXinContants.nickname)
				||!param.containsKey(WeiXinContants.sex)){
				reJs.put(StaticData.reKey.code.getKey(), StaticData.codeType.not_exist.getType());
				WorldMgr.sendMsg(channel, reJs);
				return;
			}
			image = param.getString(WeiXinContants.headimgurl);
			nickname = param.getString(WeiXinContants.nickname);
			sex = param.getIntValue(WeiXinContants.sex);
		}
		WorldMgr.UpdatePlayerInfo(user, type, image, nickname, sex,
				((InetSocketAddress)channel.remoteAddress()).getAddress().getHostAddress());
		
		reJs.put("userId", user.getID());
		reJs.put("userType", user.getUserType());
		reJs.put("userStatus", user.getUserStatus());
		reJs.put(StaticData.reKey.code.getKey(), StaticData.codeType.ok.getType());
		reJs.put(StaticData.reKey.cmd.getKey(),packet.getCode());
		WorldMgr.sendMsg(channel, reJs);
	}

}
